package com.imooc.product.controller;

import com.imooc.product.dto.CartDTO;
import com.imooc.product.VO.ProductInfoVO;
import com.imooc.product.VO.ProductVO;
import com.imooc.product.VO.ResultVO;
import com.imooc.product.dataobject.ProductCategory;
import com.imooc.product.dataobject.ProductInfo;
import com.imooc.product.service.CategoryService;
import com.imooc.product.service.ProductService;
import com.imooc.product.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Name com.imooc.product.controller.ProdectController
 * @Description
 * @Author Elwyn
 * @Version 2020/3/12
 * @Copyright 上海云辰信息科技有限公司
 **/
@RestController
@RequestMapping("/product")
public class ProdectController {
	@Autowired
	private ProductService productService;
	@Autowired
	private CategoryService categoryService;

	@GetMapping("/list")
	public ResultVO<ProductVO> list() {
		//1查询所有在架商品
		List<ProductInfo> productInfoList = productService.findUpAll();
		//获取类目type列表
		List<Integer> categoryTypeList = productInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
		//从数据库查询列木
		List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
		//构造数据
		List<ProductVO> productVOList = new ArrayList<>();
		for (ProductCategory productCategory : categoryList) {
			ProductVO productVO = new ProductVO();
			productVO.setCategoryName(productCategory.getCategoryName());
			productVO.setCategoryType(productCategory.getCategoryType());
			List<ProductInfoVO> productInfoVOList = new ArrayList<>();
			for (ProductInfo productInfo : productInfoList) {
				if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
					ProductInfoVO productInfoVO = new ProductInfoVO();
					BeanUtils.copyProperties(productInfo, productInfoVO);
					productInfoVOList.add(productInfoVO);
				}

			}
			productVO.setProductInfoVOList(productInfoVOList);
			productVOList.add(productVO);
		}
		return ResultVOUtil.success(productVOList);
	}

	@PostMapping("/listForOrder")
	public List<ProductInfo> listForOrder(@RequestBody List<String> productIdList) {
		return productService.findList(productIdList);
	}

	@PostMapping("/decreaseStock")
	public void decreaseStock(@RequestBody List<CartDTO> cartDTOList) {
		productService.decreaseStock(cartDTOList);
	}
}
